package com.investmenttechnologyservices.model;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

public abstract class EntityHolder {
    private final Entity entity;
    
	protected EntityHolder(String kind, String stringId, Key parentKey) {
	    entity = new Entity(kind, stringId, parentKey);
	}

	protected EntityHolder(String kind, long longId, Key parentKey) {
	    entity = new Entity(kind, longId, parentKey);
	}

	protected EntityHolder(String kind, String stringId) {
	    entity = new Entity(kind, stringId);
	}

	protected EntityHolder(String kind, long longId) {
	    entity = new Entity(kind, longId);
	}

	protected EntityHolder(String kind, Key parentKey) {
	    entity = new Entity(kind, parentKey);
	}

	protected EntityHolder(String kind) {
	    entity = new Entity(kind);
	}

	public EntityHolder(Entity entity) {
	    this.entity = entity;
	}

	protected Object getProperty(String name) {
		return entity.getProperty(name);
	}

	protected void setProperty(String name, Object value) {
		entity.setProperty(name, value);
	}
	
	protected void setUnindexedProperty(String name, Object value) {
		entity.setUnindexedProperty(name, value);
	}
	
	protected void removeProperty(String name) {
		entity.removeProperty(name);
	}
	
	protected void setProperty(String name, Object value, Boolean removeNull) {
		if (removeNull && value == null) {
			removeProperty(name);
		} else {
			setProperty(name, value);
		}
	}

	protected void setUnindexedProperty(String name, Object value, Boolean removeNull) {
		if (removeNull && value == null) {
			removeProperty(name);
		} else {
			entity.setUnindexedProperty(name, value);
		}
	}

	protected Key getKey() {
		return entity.getKey();
	}
	
	protected Key getParentKey() {
		return entity.getKey().getParent();
	}
	
	protected String getId() {
		return entity.getKey().getName();
	}

	protected String getParentId() {
		return entity.getKey().getParent().getName();
	}
	
	protected Double getPropertyAsZeroIfNull(String name) {
		Double amount =  (Double) entity.getProperty(name);
		return (amount==null)?0.0:amount;
	}
	
	protected void setPropertyAsNullIfZero(String name, Object value) {
		if (!value.equals(null) &&
			((Double)value) == 0.0) 
			setProperty(name, null);
		else
			setProperty(name, value);
	}
	
	public Entity asEntity() { return entity; } 
	

}
